package com.sctvcloud.renhe.ui.widget;

import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.jiongbull.jlog.JLog;
import com.sctvcloud.renhe.R;

import java.util.Calendar;

/**
 * Created by Liuyu on 2018/8/13.
 */

public class SignCalender extends FrameLayout {


    private ViewGroup rootView;
    private TextView titleView;

    private View weekTitleItem;
    private View firstDaysItem;

    private int titleTxSize = -1;
    private ColorStateList titleTxColor;
    private int weekTxSize = -1;
    private ColorStateList weekTxColor;
    private int dayTxSize = -1;
    private ColorStateList dayTxColor;

    private SparseIntArray weekPosArray;


    private final int[] itemIds = new int[]{R.id.view_item_sign_date_1, R.id.view_item_sign_date_2
            , R.id.view_item_sign_date_3, R.id.view_item_sign_date_4, R.id.view_item_sign_date_5
            , R.id.view_item_sign_date_6, R.id.view_item_sign_date_7};

    private final String[] weekNames = new String[]{"日", "一", "二", "三", "四", "五", "六"};

    public SignCalender(@NonNull Context context) {
        super(context);
        initViews(context);
    }

    public SignCalender(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initAttrs(context, attrs, 0, 0);
    }

    public SignCalender(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initAttrs(context, attrs, defStyleAttr, 0);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public SignCalender(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initAttrs(context, attrs, defStyleAttr, defStyleRes);
    }

    private void initAttrs(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.SignCalender);

        titleTxColor = a.getColorStateList(R.styleable.SignCalender_titleTxColor);
        titleTxSize = a.getDimensionPixelSize(R.styleable.SignCalender_titleTxSize, -1);
        weekTxColor = a.getColorStateList(R.styleable.SignCalender_weekTxColor);
        weekTxSize = a.getDimensionPixelSize(R.styleable.SignCalender_weekTxSize, -1);
        dayTxColor = a.getColorStateList(R.styleable.SignCalender_dayTxColor);
        dayTxSize = a.getDimensionPixelSize(R.styleable.SignCalender_dayTxSize, -1);

        initViews(context);
    }

    private void initViews(@NonNull Context context) {
        LayoutInflater inflater = LayoutInflater.from(context);
        rootView = (ViewGroup) inflater.inflate(R.layout.view_sign_calender, this, false);
        addView(rootView);
        titleView = (TextView) rootView.findViewById(R.id.view_sign_calender_title);
        titleTxSize = setTxSize(titleView, titleTxSize);
        titleTxColor = setTxColor(titleView, titleTxColor);
        weekTitleItem = inflater.inflate(R.layout.view_item_sing_calender, rootView, false);
        rootView.addView(weekTitleItem);
        setItemTxViews(weekTitleItem, weekTxColor, weekTxSize, 0, -10);

        initCalenders(inflater, rootView);
    }

    private void initCalenders(LayoutInflater inflater, ViewGroup parent) {
        initWeekPosArray();
        Calendar c = Calendar.getInstance();
//        c.add(Calendar.MONTH, 1);
        int todayWeekPos = weekPosArray.get(c.get(Calendar.DAY_OF_WEEK));
        int days = c.getActualMaximum(Calendar.DAY_OF_MONTH);
        c.set(Calendar.DAY_OF_MONTH, 1);
        int weekFirstPos = weekPosArray.get(c.get(Calendar.DAY_OF_WEEK));
        c.set(Calendar.DAY_OF_MONTH, days);
        int weekLastPos = weekPosArray.get(c.get(Calendar.DAY_OF_WEEK));
        int weekCount = (weekFirstPos + days) / 7;
        if ((weekFirstPos + days) % 7 > 0) {
            weekCount++;
        }
        int full = Integer.parseInt("1111111", 2);
        int limit = weekFirstPos == 0 ? 0 : (full << weekFirstPos) & full;

        JLog.e("ddddd  twp=" + todayWeekPos + "  wfp=" + weekFirstPos + "  wc=" + weekCount + "   wlp=" + weekLastPos
                + "  1<<1=" + (1 << 1) + "  1>>1=" + (1 >> 1) + "  1<<0=" + (1 << 0) + "   limit=" + limit
                + "  lf=" + Integer.toBinaryString(limit) + "  fuu=" + full);
        View v = inflater.inflate(R.layout.view_item_sing_calender, rootView, false);
        parent.addView(v);
        setItemTxViews(v, dayTxColor, dayTxSize, limit, 1 - weekFirstPos);
        for (int i = 1; i < weekCount - 1; i++) {
            View vv = inflater.inflate(R.layout.view_item_sing_calender, rootView, false);
            parent.addView(vv);
            setItemTxViews(vv, dayTxColor, dayTxSize, 0, i * 7 - weekFirstPos + 1);
        }
        limit = 6 - weekLastPos;
        JLog.e("ddddd  will sure last limit=" + limit);
        if (limit > 0) {
            limit = (full >> limit) & full;
        }
//        todayWeekPos = weekCount * 7 - weekFirstPos - days - 7;
        JLog.e("ddddd  last limit=" + limit + "   lb=" + Integer.toBinaryString(limit));
        v = inflater.inflate(R.layout.view_item_sing_calender, rootView, false);
        parent.addView(v);
        setItemTxViews(v, dayTxColor, dayTxSize, limit, weekCount * 7 - 6 - weekFirstPos);
    }

    private void initWeekPosArray() {
        weekPosArray = new SparseIntArray();
        weekPosArray.put(Calendar.SUNDAY, 0);
        weekPosArray.put(Calendar.MONDAY, 1);
        weekPosArray.put(Calendar.TUESDAY, 2);
        weekPosArray.put(Calendar.WEDNESDAY, 3);
        weekPosArray.put(Calendar.THURSDAY, 4);
        weekPosArray.put(Calendar.FRIDAY, 5);
        weekPosArray.put(Calendar.SATURDAY, 6);
    }

    private void setItemTxViews(View item, ColorStateList colorStateList, int txSize, int limit, int start) {
        if (item == null) {
            return;
        }
        int m = 1;//用于确定是让前面的view不显示还是让后面的view不显示
        int n = 0;
        if (limit != 0) {
            m = limit / Math.abs(limit);
        }
        JLog.e("ddddd   m=" + m + "  start=" + start);
        for (int i = 0; i < itemIds.length; i++) {
            TextView tv = (TextView) item.findViewById(itemIds[i]);
            setTxColor(tv, colorStateList);
            setTxSize(tv, txSize);
            int j = 1 << i;
            JLog.e("ddddd        ------");
            JLog.e("dddddv   1<<" + i + " =" + j + "   j b=" + Integer.toBinaryString(j) + "   limit=" + limit
                    + "   l b=" + Integer.toBinaryString(limit));
            if (limit > 0 && ((1 << i) & limit) <= 0) {
//                if (i < limit) {
//                }
                tv.setVisibility(INVISIBLE);
            } else {
                if (start < -8) {
                    tv.setText(weekNames[i]);
                } else {
                    tv.setText(start + i + "");
                }
//                if (limit == -1 || i > 0) {
//                    tv.setVisibility(INVISIBLE);
//                } else {

//                }
            }
        }
    }

    /**
     * 设置文字的颜色
     *
     * @param tv             目标文字控件
     * @param colorStateList 颜色
     * @return 设置好的颜色，如果控件为空，则返回空
     */
    private ColorStateList setTxColor(TextView tv, ColorStateList colorStateList) {
        if (tv == null) {
            return null;
        }
        if (colorStateList != null) {
            tv.setTextColor(colorStateList);
            return colorStateList;
        } else {
            return tv.getTextColors();
        }
    }

    /**
     * 设置文字的大小
     *
     * @param tv   目标文字控件
     * @param size 大小
     * @return 设置好的大小，如果控件为空，则返回-1
     */
    private int setTxSize(TextView tv, int size) {
        if (tv == null) {
            return -1;
        }
        if (size > 0) {
            tv.setTextSize(size);
            return size;
        } else {
            return (int) tv.getTextSize();
        }
    }
}
